// 运行时配置

import { RunTimeLayoutConfig, history, request } from '@umijs/max';
import { Modal, message } from 'antd';
import RightContent from './components/RightContent';
import { getUserInfo as getUserInfoFromApi } from './services/userApi';
import { getToken, clearToken } from './utils/authInterceptor';
import { getUserInfo as getUserInfoFromCookie } from './utils/cookieUtils';

// 请求拦截器配置将通过umi的request配置项来实现

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{
  name: string;
  userInfo?: USER.UserModel;
  currentUser?: USER.UserModel;
}> {
  // 检查是否有token
  const token = getToken();
  if (!token) {
    return { name: '未登录' };
  }

  // 优先从cookie获取用户信息，避免额外的API请求
  let userInfo = getUserInfoFromCookie();

  // 如果cookie中没有用户信息，则从API获取
  if (!userInfo) {
    try {
      userInfo = await getUserInfoFromApi();
      console.log('从API获取用户信息成功:', userInfo);
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果token无效，清除token并跳转到登录页
      clearToken();
      if (window.location.pathname !== '/login') {
        history.replace('/login');
      }
    }
  } else {
    console.log('从cookie获取用户信息成功:', userInfo);
  }

  return {
    name: userInfo?.nickname || userInfo?.username || '管理员',
    userInfo,
    currentUser: userInfo
  };
}

/**
 * 配置 layout
 *
 * 参考链接：https://umijs.org/docs/max/layout-menu#%E8%BF%90%E8%A1%8C%E6%97%B6%E9%85%8D%E7%BD%AE
 * @returns
 */
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
    },
    fixSiderbar: true,
    layout: 'mix',
    splitMenus: false,
    // navTheme: 'realDark',
    contentWidth: 'Fluid',
    colorPrimary: '#1890ff',
    siderMenuType: 'sub',
    fixedHeader: true,
    siderWidth: 188,
    // 通过token修改主题色
    token: {
      sider: {
        colorMenuBackground: '#ffffff',
      },
      header: {
        colorBgHeader: '#001529',
        colorHeaderTitle: '#ffffff',
        heightLayoutHeader: 48,
      },
      pageContainer: {},
    },
    rightContentRender: () => <RightContent />,
    logout: (initialState: any) => {
      console.log('登出操作:', initialState);
      Modal.confirm({
        title: '注销登录',
        content: '确定要注销登录吗？',
        okText: '确定',
        cancelText: '取消',
        okButtonProps: {
          danger: true,
        },
        onOk: () => {
          // 清除token
          clearToken();
          // 跳转到登录页
          history.replace('/login');
        },
      });
    },
    // actionsRender: (props) => {
    //   if (props.isMobile) return [];
    //   if (typeof window === 'undefined') return [];
    //   return [
    //     <InfoCircleFilled key="InfoCircleFilled" />,
    //     <QuestionCircleFilled key="QuestionCircleFilled" />,
    //     <GithubFilled key="GithubFilled" />,
    //   ];
    // },
  };
};
